package com.scut.online_black_market.service.impl;

import com.scut.online_black_market.exception.VerifyCodeException;
import com.scut.online_black_market.service.MailService;
import com.scut.online_black_market.utility.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

/**
 * create by yellowBroke on 2020/11/2 11:38
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private RedisUtil redisUtil;

    @Override
    @Async
    public void sendMail(String to) {
        String validateCode = getValidateCode();

        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(from);
        message.setTo(to);
        message.setSubject("华工线上黑市注册验证码");
        message.setText("本次注册验证码： " + validateCode + "。 1hour内有效，打死也不要告诉别人哦！");
        mailSender.send(message);
        redisUtil.set(to,validateCode,60 * 60);
        log.info("验证码已发送到 {}",to);
    }

    @Override
    public void validateCode(String mail, String validateCode) throws VerifyCodeException {
        if (redisUtil.getExpire(mail) < 0)
            throw new VerifyCodeException("验证码超时，请重新发送！");
        String code = (String) redisUtil.get(mail);
        if (code == null || !code.equals(validateCode)) {
            throw new VerifyCodeException("验证失败");
        }
    }

    private static String getValidateCode(){
         return String.valueOf(100000 + new Random().nextInt(899999));
    }
}
